import {Component, OnInit, AfterViewInit, OnDestroy, ElementRef} from '@angular/core';
import {DisplayService} from "../display.service";
import {NingxiaPanelComponent} from "../ningxia-panel/ningxia-panel.component";
import {MapUiService} from '../../one-map/map-ui.service';
import * as echarts from "echarts";
import {HttpClient} from '@angular/common/http';
import {FetchService} from 'src/app/core/net/fetch.service';
import * as _ from 'lodash';

@Component({
  selector: 'app-ningxia',
  templateUrl: './ningxia.component.html',
  styleUrls: ['../river/river.component.scss', './ningxia.component.scss']
})
export class NingxiaComponent implements OnInit, AfterViewInit, OnDestroy {
  points: any[] = [];
  points2: any[] = [];
  geoserverUrl = (window as any).environment.geoserverUrl;
  modalShow = false;
  pieOpt: any = {
    legend: {
      orient: 'vertical',
      right: 5,
      bottom: 10,
      textStyle: {
        color: '#ffffff'
      },
      data: ['生活用水', '生态用水', '工业用水', '农业用水']
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        type: 'pie',
        radius: ['35%', '60%'],
        label: {
          normal: {
            formatter: '({c}亿m³) {per|{d}%}',
            color: '#4CC5F8',
            position: 'outer',
            margin: '3%',
            rich: {
              b: {
                color: '#0DC9DC',
                fontSize: 12,
                lineHeight: 18,
                align: 'center'
              },
              c: {
                color: '#ffffff'
              },
              per: {
                color: '#4CC5F8',
                padding: [2, 4],
                borderRadius: 4
              }
            }
          }
        },
        itemStyle: {
          normal: {
            color: (params) => {
              const colorList = [
                ['#EED2EE', '#E066FF', '#CD00CD'],
                ['#63D360', '#089C04', '#1FCD1B'],
                ['#87CEFF', '#4F94CD', '#1C86EE'],
                ['#4CC5F8', '#56E8F2', '#84F5DE']
              ];
              return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                {offset: 0, color: colorList[params.dataIndex][0]},
                {offset: 0.5, color: colorList[params.dataIndex][1]},
                {offset: 1, color: colorList[params.dataIndex][2]}
              ]);
            }
          }
        },
        data: [

          {value: 3.634, name: '生活用水'},
          {value: 4.786, name: '工业用水'},
          {value: 2.408, name: '生态用水'},
          {value: 54.497, name: '农业用水'}
        ]
      }
    ]
  };

  chartMergeOpt;
  chartMergeOpt2;
  table1Data = [
    {a1: '银川市'},
    {a1: '石嘴山市'},
    {a1: '吴忠市'},
    {a1: '固原市'},
    {a1: '中卫市'},
  ];
  table2Data = [
    {a1: '兴庆区'},
    {a1: '金凤区'},
    {a1: '西夏区'},
    {a1: '灵武市'},
    {a1: '永宁县'},
    {a1: '贺兰县'},
  ];
  clickIdArr: any[] = ['MA761JBE7', 'MA761GDE1', '763236628', '750826119', '710643190', '455130901', '227695003'];
  downIdArr: any[] = ['6405020120', '6405020110', '6405210100', '6403814025', '6402050600'];

  videos: any[] = [
    {
      // 七星渠进水闸闸后拱桥
      id: '0abb65d0d5b94954a5f8f3541ad2ef09',
      imgSrc: 'video1.png'
    },
    {
      // 泉眼山前池1
      id: '650f23e7de1f437695bb254c6f234b0f',
      imgSrc: 'video2.png'
    },
    {
      // 石嘴山新电厂
      id: '5a0d3261c2d749a4bf047ba1788641c4',
      imgSrc: 'video3.png'
    },
    // {
    //   id: 'a659467838284841946268036a6e09ec',
    //   imgSrc: 'video4.png'
    // }
  ];

  constructor(private dispService: DisplayService, private mapService: MapUiService, private elementRef: ElementRef, private http: HttpClient, private fetchService: FetchService
  ) {
  }

  ngOnInit(): void {
    this.dispService.typeChange.next('ningxia');
    // this.dispService.createSidePane(null);
    this.http.get(`${this.geoserverUrl}water_resource_dispatch_nx/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=water_resource_dispatch_nx%3Aview_qysqs&maxFeatures=5000&outputFormat=application%2Fjson`).subscribe((res: any) => {
      this.points = res.features.map(f => {
        return f.properties;
      });
    });
    this.http.get(`${this.geoserverUrl}water_resource_dispatch_nx/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=water_resource_dispatch_nx%3Aview_qysqs_st&maxFeatures=5000&outputFormat=application%2Fjson`).subscribe((res: any) => {
      this.points2 = res.features.map(f => {
        return f.properties;
      });
    });
    this.getTable1Data();
  }

  ngAfterViewInit(): void {
    this.mapService.getMapInstance().then(() => {
      setTimeout(() => {
        this.points.map((p, i) => {
          const point = this.elementRef.nativeElement.querySelector(`.point${i}`);
          this.dispService.addOverlay(point, [p.x, p.y]);
        });
        this.points2.map((p, i) => {
          const point = this.elementRef.nativeElement.querySelector(`.point2_${i}`);
          this.dispService.addOverlay(point, [p.x, p.y]);
        });
      }, 1000);
    });
    this.queryQYSQS();
  }

  ngOnDestroy(): void {
    this.dispService.clearOverlay();
  }

  queryQYSQS(): void {
    this.fetchService.post("intake/wrsWiuU/query", {}).subscribe((data: any) => {
      this.points = this.points.map(p => {
        data.map(d => {
          if (d.wiu_cd == p.wiu_cd) {
            p = {
              ...p,
              ...d,
              eClick: this.clickIdArr.indexOf(d.wiu_cd) > -1,
            };
          }
        });
        return p;
      });
    });
    this.fetchService.post("intake/wrsWiuSt/queryByStcd", {}).subscribe((data: any) => {
      this.points2 = this.points2.map(p => {
        data.map(d => {
          if (d.wiust_cd == p.wiust_cd) {
            p = {
              ...p,
              ...d,
              className: this.downIdArr.indexOf(d.wiust_cd) > -1 ? 'down' : ''
            };
          }
        });
        return p;
      });
    });
  }

  // 查询宁夏城市数据
  getTable1Data(): void {
    this.fetchService.post("muw/wrsMuwIrrData/statistic", {})
      .subscribe((res: any) => {
        const area = [];
        const tData = [];
        const pieData = [0, 0, 0, 0];
        res.map(item => {
          if (area.indexOf(item.name) == -1) {
            area.push(item.name);
            tData.push({name: item.name, id: item.id});
          }
          if (item.pname == '生活用水') {
            pieData[0] += item.val;
          }
          if (item.pname == '工业用水') {
            pieData[1] += item.val;
          }
          if (item.pname == '农业用水') {
            pieData[2] += item.val;
          }
          if (item.pname == '生态用水') {
            pieData[3] += item.val;
          }
        });

        res.map(item => {
          for (const x of tData) {
            if (item.name == x.name) {
              x[item.pname] = item.val;
            }
          }
        });

        this.table1Data = tData.map(row => {
          return {
            ...row, ...{total: (row['农业用水'] + row['工业用水'] + row['生活用水'] + row['生态用水']).toFixed(3)}
          };
        });

        this.chartMergeOpt = {
          series: [
            {
              data: [
                {value: pieData[0].toFixed(2), name: '生活用水'},
                {value: pieData[1].toFixed(2), name: '工业用水'},
                {value: pieData[2].toFixed(2), name: '农业用水'},
                {value: pieData[3].toFixed(2), name: '生态用水'}
              ]
            }
          ]
        };
        this.chartMergeOpt2 = {
          series: [
            {
              data: [
                {value: pieData[0].toFixed(2), name: '生活用水'},
                {value: pieData[1].toFixed(2), name: '工业用水'},
                {value: pieData[2].toFixed(2), name: '农业用水'},
                {value: pieData[3].toFixed(2), name: '生态用水'}
              ]
            }
          ]
        };
        this.getTable2Data(this.table1Data[0]['id']);
      });
  }

  // 查询宁夏城市区域数据
  getTable2Data(id): void {
    this.fetchService.post("muw/wrsMuwIrrData/statistic", {id: id})
      .subscribe((res: any) => {
        const area = [];
        const tData = [];

        res.map(item => {
          if (area.indexOf(item.name) == -1) {
            area.push(item.name);
            tData.push({name: item.name, id: item.id});
          }
        });

        res.map(item => {
          for (const x of tData) {
            if (item.name == x.name) {
              x[item.pname] = item.val;
            }
          }
        });

        this.table2Data = tData.map(row => {
          return {
            ...row, ...{total: (row['农业用水'] + row['工业用水'] + row['生活用水'] + row['生态用水']).toFixed(3)}
          };
        });
      });
  }

  rowClick(rowData): void {
    this.getTable2Data(rowData.id);
    const chartData = [];
    for (const key in rowData) {
      if (key == '农业用水' || key == '工业用水' || key == '生活用水' || key == '生态用水') {
        chartData.push({name: key, value: rowData[key]});
      }
    }
    console.log(chartData);
    this.chartMergeOpt2 = {
      series: [{

        data: chartData
      }]
    };
  }
}
